package com.common.factory;

import cn.hutool.json.JSONObject;
import com.common.authentication.Oauth2ModeAuthentication;
import com.common.pojo.AbstractOauth2AccountModeWrapper;
import com.common.strategy.AccountTypeStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.Map;

/**
 * @Description: 包含登陆方式策略的一个包装类
 * @Date: 2025/6/7 11:35
 */
public abstract class AbstractOauth2AuthenticationFactoryStrategyWrapper<M extends AbstractOauth2AccountModeWrapper, A extends Oauth2ModeAuthentication, S extends AccountTypeStrategy<A, M>> implements Oauth2AuthenticationFactory<M, A> {
    protected abstract M createMode(JSONObject bodyJsonObject);

    @Autowired(required = false)
    private Map<String, AccountTypeStrategy> loginTypeStrategyMap;

    /**
     * 模版方法，用来生成最终需要的token
     *
     * @param bodyJsonObject
     * @return
     */
    @Override
    public A authentication(JSONObject bodyJsonObject) {
        M mode = createMode(bodyJsonObject);
        if (ObjectUtils.isEmpty(mode) || ObjectUtils.isEmpty(mode.getAccountType()) ) {
            return null;
        }
        if (CollectionUtils.isEmpty(loginTypeStrategyMap)){
            return null;
        }
        String accountType = mode.getAccountType();
        if (!loginTypeStrategyMap.containsKey(accountType)){
            return null;
        }
        S strategy = (S) loginTypeStrategyMap.get(mode.getAccountType());
        A authentication = strategy.login(mode);
        if (!ObjectUtils.isEmpty(authentication)){
            authentication.setAuthenticated(true);
        }
        return authentication;
    }
}
